package top.lishuoboy.jwt.jwt.config;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import top.lishuoboy.dependency.base.json.HuJsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author admin
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws IOException {
        resp.setContentType("text/html;charset=UTF8");
        String token = req.getHeader("token");
        if (StrUtil.isEmpty(token)) {
//            throw new Exception("token不能为空,请先获取token");
//            resp.sendRedirect("error?msg=token is null, login first");
            resp.getWriter().write("token 为空, 请先登录");
            return false;
        }
        try {
            DecodedJWT decode = JWT.decode(token);
            String payload = Base64Decoder.decodeStr(decode.getPayload());

            Map<String, Object> payloadMap = HuJsonUtil.toMap(payload);
            long validTime = (Long) payloadMap.get("validTime");
            if (DateUtil.current() > validTime) {
                resp.getWriter().write("token过期");
                return false;
            }
            return true;
        } catch (Exception e) {
            log.warn("token无效，解码错误", e);
            resp.getWriter().write("token无效，解码错误");
            return false;
        }
    }
}
